import { Controller, Sse } from '@nestjs/common';
import { SseService } from './sse.service';
import { Observable } from 'rxjs';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';

@Controller('sse')
export class SseController {
  constructor(private readonly sseService: SseService) {}

  @Sse('stream')
  stream() {
    return new Observable((observer) => {
      observer.next({ data: { msg: 'aaa' } });

      setTimeout(() => {
        observer.next({ data: { msg: 'bbb' } });
      }, 2000);

      setTimeout(() => {
        observer.next({ data: { msg: 'ccc' } });
      }, 5000);
    });
  }

  /**
    const eventSource = new EventSource('http://127.0.0.1:3333/api/sse/stream2');
    eventSource.onmessage = ({ data }) => {
      console.log('New message', JSON.parse(data.toString()));
    };
   */
  @Sse('stream2')
  stream2() {
    return new Observable((observer) => {
      const path = join(process.cwd(), 'package.json');
      const buffer = readFileSync(path);
      const json = JSON.parse(buffer.toString('utf-8'));
      // console.log(json);
      observer.next({ data: { msg: json } });
    });
  }
}
